<template>
  <div class="live-code-manage" v-loading="isAjaxing">
    <el-card>
      <div class="live-code-content">
        <h3>活码管理</h3>
        <div class="live-code-header-btn" v-if="tableSelect.length >0">
          <span class="select-length">已选择 {{ tableSelect.length }} 条</span>
          <el-link icon="el-icon-upload2" @click.prevent="exportSelect(tableSelect)">导出选中</el-link>
          <el-link icon="el-icon-download" @click.prevent="downloadSelect">下载选中二维码</el-link>
          <el-link icon="el-icon-delete" @click.prevent="deleteConfirm(tableSelect)">移至回收站</el-link>
        </div>
        <div class="live-code-header-btn" v-else>
          <el-button class="create-code-btn" type="primary" size="mini" icon="el-icon-plus" @click="$router.push('/user-center/live-code/create')">创建活码</el-button>
          <el-dropdown @command="changeType">
            <el-button type="success" size="mini">
              <span v-if="query.type.length == 2">活码类型</span>
              <span v-else-if="query.type[0] == 1">普通活码</span>
              <span v-else-if="query.type[0] == 2">分组活码</span>
              <i class="el-icon-arrow-down"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="[1]">普通活码</el-dropdown-item>
                <el-dropdown-item :command="[2]">分组活码</el-dropdown-item>
                <el-dropdown-item :command="[1,2]">显示全部</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <el-table :data="liveCodeTableData" :border="false" @selection-change="selectTableCheckbox" :max-height="tableMaxHeight">
          <el-table-column type="selection">
          </el-table-column>
          <el-table-column prop="id" label="ID" width="65">
          </el-table-column>
          <el-table-column prop="name" label="群名称" show-tooltip-when-overflow>
          </el-table-column>
          <el-table-column prop="code" label="二维码缩略图" min-width="100px">
            <template #default="{ row }">
              <img :src="baseUrl +'/' + row.code" @click="showDownload(row)" width="75" height="75">
            </template>
          </el-table-column>
          <el-table-column prop="type" label="活码类型">
            <template #default="{ row }">
              <span>{{ row.type == 1 ? '普通活码' : '分组活码' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="活码状态">
            <template #default="{ row }">
              <el-switch :loading="row.stateChangeLoading" v-model="row.state" :active-value="1" :inactive-value="0" :beforeChange="()=>changeState(row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="160px"></el-table-column>
          <el-table-column>
            <template #default>
              <div class="prefix-title">
                总数量<br>
                有效数量<br>
                最近失效
              </div>
            </template>
          </el-table-column>
          <el-table-column label="群活码数量" width="80px">
            <template #default="scope">
              <div class="live-code-number">
                {{ scope.row.code_count }}<br>
                {{ scope.row.code_count_effective }}<br>
                {{ scope.row.code_count_invalid }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="45px">
            <template #default>
              <div class="prefix-title">
                今日<br>
                累计
              </div>
            </template>
          </el-table-column>
          <el-table-column label="扫码次数" width="70px">
            <template #default="scope">
              <div class="live-code-number">
                {{ scope.row.today_num }}<br>
                {{ scope.row.num }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="扫码人数" width="70px">
            <template #default="scope">
              <div class="live-code-number">
                {{ scope.row.today_people }}<br>
                {{ scope.row.people }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="80px">
            <template #default>
              <div class="split-line"></div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200px">
            <template #default="scope">
              <div class="operate-btn">
                <img src="/img/table-operate-images/curve_icon.png" alt="curve_icon" title="查看数据" @click="statisticsData.shortData.name = scope.row.name;statisticsData.shortData.short_url=scope.row.domain_name +'/' + scope.row.url;statisticsData.showStatisticsDialog=true;statisticsData.formData.type=scope.row.type">
                <img src="/img/table-operate-images/edit_icon.png" alt="edit_icon" title="编辑" @click="editShow(scope.row)">
                <img src="/img/table-operate-images/app_plugin_icon.png" alt="app_plugin_icon" title="二维码管理" @click="openQRcodeManage(scope.row)">
                <img src="/img/table-operate-images/cutover_icon.png" alt="cutover_icon" title="切换入口域名" @click="changeDomainDialog = true;changeDomainForm.domain = scope.row.domain;changeDomainForm.live_code_id = scope.row.id">
                <img src="/img/table-operate-images/delete_icon.png" alt="delete_icon" title="删除" @click="deleteConfirm([scope.row.id])">
              </div>
            </template>
          </el-table-column>
          <template v-slot:empty>
            <div class="empty-box">
              <img class="empty-img" src="/img/404-images/empty.png" alt="暂无内容">
              <div>暂无数据</div>
            </div>
          </template>
        </el-table>
      </div>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="query.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
  </div>

  <el-dialog :close-on-click-modal="false" title="编辑" v-model="editDialog.showEditDialog" :before-close="beforeClose" width="500px" custom-class="edit-dialog">
    <el-form :model="editForm" ref="editDialogFormRef" label-position="top" :rules="rules">
      <div class="edit-dialog-header">
        <div class="edit-header-left">
          <img class="qrcode" :src="baseUrl +'/' + editForm.code" />
          <el-button type="primary" plain @click="download(editForm.name,baseUrl +'/' + editForm.code)">下载二维码</el-button>
        </div>
        <div class="edit-header-right">
          <el-form-item label="活码名称" prop="name">
            <el-input placeholder="请输入活码名称" v-model="editForm.name"></el-input>
          </el-form-item>
          <div class="edit-header-link">
            <div>
              <span>活码链接：</span>{{ `http://${editForm.domain_name}/${editForm.url}` }}
            </div>
            <img src="/img/my-short-chain-images/short-chain-management-images/copy_icon.png" alt="copy_icon">
          </div>
        </div>
      </div>
      <el-form-item label="活码页标题">
        <el-input placeholder="请输入活码页标题名称" v-model="editForm.title"></el-input>
      </el-form-item>
      <el-form-item label="引导文字" prop="remark" v-if="editForm.type == 2">
        <el-input type="textarea" rows="4" placeholder="展示在二维码下方的引导文字" resize="none" v-model="editForm.remark"></el-input>
      </el-form-item>
      <el-form-item label="是否开启密码访问">
        <el-switch v-model="editForm.password_state" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="访问密码" v-if="editForm.password_state == 1" prop="password">
        <el-input placeholder="请设置密码" v-model="editForm.password"></el-input>
      </el-form-item>
      <el-form-item v-if="editForm.type == 2">
        <template #label>
          客服功能 <span class="iconfont icon-wenti_yiwen"></span>
          <span class="msg-tips">选择监控目标在那种状态下报警</span>
        </template>
        <el-radio-group v-model="editForm.cs_code_state">
          <el-radio :label="1">开启</el-radio>
          <el-radio :label="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="客服头像" v-if="editForm.cs_code_state == 1" prop="cs_img">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl+'/upload'"
          :headers="uploadHeader"
          :data="{path:'kefu_img'}"
          :show-file-list="false"
          accept="jpg,png,jpeg"
          :on-success="(response)=>handleAvatarSuccess('cs_img',response)"
        >
          <img v-if="editForm.cs_img" :src="`${baseUrl}/${editForm.cs_img}`" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="上传客服二维码" v-if="editForm.cs_code_state == 1" prop="cs_code">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl+'/upload'"
          :headers="uploadHeader"
          :data="{path:'kefu_code'}"
          :show-file-list="false"
          :on-success="(response)=>handleAvatarSuccess('cs_code',response)"
        >
          <img v-if="editForm.cs_code" :src="`${baseUrl}/${editForm.cs_code}`" class="avatar">
          <i v-else class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <template #label>
          跳转模式 <span class="iconfont icon-wenti_yiwen"></span>
          <span class="msg-tips">选择监控目标在那种状态下报警</span>
        </template>
        <el-radio-group v-model="editForm.jump_type">
          <el-radio :label="1">防封跳转</el-radio>
          <el-radio :label="2">极速跳转</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="editForm.type == 2">
        <template #label>
          安全提示 <span class="iconfont icon-wenti_yiwen"></span>
          <span class="msg-tips">选择监控目标在那种状态下报警</span>
        </template>
        <el-radio-group v-model="editForm.tips">
          <el-radio :label="1">开启</el-radio>
          <el-radio :label="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider>阅读即焚</el-divider>
      <el-switch v-model="editForm.burn" :active-value="1" :inactive-value="0"></el-switch>
      <div class="read-tips">注：活码被阅读一次后即失效</div>
<!--      <el-divider>限制地区访问</el-divider>-->
<!--      <el-switch v-model=""></el-switch>-->
      <el-form-item>

      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="default" size="mini" @click="editDialog.showEditDialog = false">取消</el-button>
      <el-button type="primary" size="mini" @click="editSubmit" :loading="isSubmit">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog custom-class="changeDomainDialog" title="切换入口域名" v-model="changeDomainDialog" :before-close="(done)=>isSubmit ? $message.warning('暂时无法关闭') : done()">
    <el-form label-position="top" :model="changeDomainForm" ref="changeDomainRef" :rules="{domain:[{required:true,message:'请选择入口域名',trigger:'change'}]}">
      <el-form-item prop="domain">
        <template #label>
          <strong>入口域名</strong>
        </template>
        <el-select v-model="changeDomainForm.domain" style="width: 100%">
          <el-option v-for="n in domainList" :key="n.id" :label="n.domain" :value="n.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button size="small" type="default" @click="changeDomainDialog = false">取消</el-button>
      <el-button size="small" type="primary" @click="changeDomainSubmit" :loading="isSubmit">确认</el-button>
    </template>
  </el-dialog>
  <dataStatistic v-if="statisticsData.showStatisticsDialog" :statisticsData="statisticsData"></dataStatistic>
</template>

<script>
import { reactive, getCurrentInstance, toRefs, createVNode, onMounted, onUnmounted } from 'vue'
import { changeLiveCodeDomain, deleteliveCode, fallList, getliveCodeList, updateliveCode } from '@/axios/userRequest'
import { computedPage, downloadImgZip, downloadSome, getImgBase64 } from '@/utils/utils'
import liveCodeDownloadCode from '@/components/usersComponents/liveCode/liveCodeDownloadCode'
import dataStatistic from '@/components/usersComponents/statistics/dataStatistics'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import baseUrl from '@/axios/baseUrl'

export default {
  components:{
    dataStatistic
  },
  setup(){
    const { proxy } = getCurrentInstance()
    const router = useRouter()
    let Store = useStore()
    const state = reactive({
      changeDomainDialog:false,
      isAjaxing:true,
      isSubmit:false,
      tableMaxHeight: window.innerHeight - 350,
      uploadHeader:{'token':localStorage.getItem('userCenter_token')},
      query:{
        type:[1,2],
        page:1,
        limit:10
      },
      liveCodeTableData:[],
      total:0,
      groupData:{
        showDelGroupDialog:false
      },
      editDialog:{
        showEditDialog: false
      },
      tableSelect:[],
      editForm:{},
      rules:{
        name:[{required:true,message:'请输入活码名称',trigger:'blur'}],
        remark:[{required:true,message:'请输入引导文字',trigger:'blur'}],
        password:[{required:true,message:'请输入访问密码',trigger:'blur'}],
        cs_code:[{required:true,message:'请上传客服二维码',trigger:'blur'}],
        cs_img:[{required:true,message:'请上传客服头像',trigger:'blur'}]
      },
      changeDomainForm:{
        live_code_id:'',
        domain:undefined
      },
      domainList:[],
      statisticsData:{
        type:2,
        showStatisticsDialog:false,
        shortData:{},
        formData:{// 查询数据
          type: 1,// 短链查询
          code_id: null,// 短链id
        }
      }
    })
    const resizeHeight = ()=>state.tableMaxHeight = window.innerHeight - 350
    onMounted(()=>window.addEventListener('resize',resizeHeight))
    onUnmounted(()=>window.removeEventListener('resize',resizeHeight))

    const changeType = (type) => {
      state.query.type = type
      state.query.page = 1
      getList()
    }

    const getList = () => {
      state.isAjaxing = true
      getliveCodeList(state.query).then(res=>{
        if(res.code == 0){
          state.liveCodeTableData = res.data.data
          state.total = res.data.total
        }else{
          proxy.$message.error(res.msg)
        }
        state.isAjaxing = false
      })
    }
    getList()

    const editSubmit = () => {
      proxy.$refs.editDialogFormRef.validate(bool=>{
        if(bool){
          state.isSubmit = true
          updateliveCode(state.editForm).then(res=>{
            state.isSubmit = false
            if(res.code == 0){
              proxy.$message.success('修改成功')
              state.editDialog.showEditDialog = false
              getList()
            }else{
              proxy.$message.error(res.msg)
            }

          })
        }
      })
    }

    const selectTableCheckbox = val =>{
      state.tableSelect = val.map(item=>item.id)
    }
    const openQRcodeManage = row =>{
      if(row.type == '2'){
        router.push(`/user-center/live-code/group/${row.id}`)
      }else{
        router.push(`/user-center/live-code/ordinary/${row.id}`)
      }
    }

    const handleSizeChange = (val) => {
      state.query.limit = val
      state.query.page = 1
      getList()
    }

    const handleCurrentChange = (val) => {
      state.query.page = val
      getList()
    }

    const editShow = (row)=>{
      state.editForm = {
        ...row
      }
      state.editDialog.showEditDialog = true
    }

    const changeState = (row)=>{
      row.stateChangeLoading = true
      return new Promise((resolve, reject)=>{
        updateliveCode({
          id:row.id,
          type:row.type,
          state:row.state == 0 ? 1 : 0
        }).then(res=>{
          if(res.code == 0){
            proxy.$message.success('修改成功')
            resolve(true)
          }else{
            proxy.$message.error(res.msg)
            reject()
          }
          row.stateChangeLoading = false
        })
      })
    }

    const beforeClose = (done) => {
      if(state.isSubmit){
        proxy.$message.warning('暂时无法关闭')
      }else{
        done()
      }
    }

    const download = (name,url)=>{
      downloadSome(url,name)
    }

    const handleAvatarSuccess = (name,response)=>{
      if(response.code == 0){
        state.editForm[name] = response.data.path
      }else{
        proxy.$message.error(response.msg)
      }
    }

    const deleteConfirm = (id) => {
      proxy.$confirm('删除活码后，一切有关数据将会被删除，删除后活码不可被访问。是否删除？','删除活码',{
        closeOnClickModal:false,
        customClass:'commonMessageBox',
        type: 'warning',
      }).then(()=>{
        state.isAjaxing = true
        deleteliveCode({id}).then(res=>{
          if(res.code == 0){
            proxy.$message.success('删除成功')
            state.query.page = computedPage(id.length,state.query.page,state.query.limit,state.total)
            getList()
          }else{
            state.isAjaxing = false
            proxy.$message.error(res.msg)
          }
        })
      })
    }

    const exportSelect = id=>{
      window.open(baseUrl+'/code_select_execl?id='+id)
    }

    const showDownload = (row) => {
      proxy.$confirm(createVNode(liveCodeDownloadCode,{
        codeUrl:baseUrl +'/' + row.code,
        url:row.domain_name +'/' + row.url
      }),'下载二维码',{
        closeOnClickModal:false,
        customClass:'commonMessageBox',
        confirmButtonText:'确认下载'
      }).then(()=>{
        downloadSome(baseUrl +'/' + row.code,'asdad.png')
      })
    }

    const downloadSelect = ()=>{
      let imgArr = []
      state.liveCodeTableData.forEach(item=>{
        if(state.tableSelect?.includes(item.id)){
          let image = new Image()
          image.setAttribute('crossOrigin', 'anonymous')
          // image.src = baseUrl+'/'+item.code // 服务器短链二维码
          image.src = '/img/404-images/下载测试二维码.png' // 本地环境测试图片
          image.onload = ()=>{
            imgArr.push({ name: item.name, baseImg: getImgBase64(image) })
            imgArr.length === state.tableSelect.length ? downloadImgZip(imgArr,`活码管理列表`) : ''
          }
        }
      })
    }

    const getDomainList = ()=>{
      fallList({type:1}).then(res=>{
        if(res.code == 0){
          state.domainList = res.data.data['1']
          Store.commit('userStore/changeStoreState',['LiveCodeInDomainList',res.data.data['1']])
        }else{
          proxy.$message.error(res.msg)
        }
      })
    }

    const changeDomainSubmit = () => {
      proxy.$refs.changeDomainRef.validate(bool=>{
        if(bool){
          state.isSubmit = true
          changeLiveCodeDomain(state.changeDomainForm).then(res=>{
            if(res.code == 0){
              let index = state.liveCodeTableData.findIndex(item=>item.id === state.changeDomainForm.live_code_id)
              state.liveCodeTableData[index].domain = state.changeDomainForm.domain
              state.changeDomainDialog = false
              proxy.$message.success(res.msg)
            }else{
              proxy.$message.error(res.msg)
            }
            state.isSubmit = false
          })
        }
      })
    }

    if(Store.state.userStore.LiveCodeInDomainList){
      state.domainList = Store.state.userStore.LiveCodeInDomainList
    }else{
      getDomainList()
    }

    return{
      ...toRefs(state),
      baseUrl,
      selectTableCheckbox,
      openQRcodeManage,
      handleSizeChange,
      handleCurrentChange,
      editShow,
      editSubmit,
      changeState,
      download,
      beforeClose,
      handleAvatarSuccess,
      deleteConfirm,
      exportSelect,
      showDownload,
      downloadSelect,
      changeDomainSubmit,
      changeType
    }
  }
}



</script>

<style lang="less" scoped>
.edit-dialog{
  .el-dialog__body{
    .el-form{
      .edit-dialog-header{
        display: flex;
        justify-content: space-between;
        flex: 1;
        margin-bottom: 32px;
        .edit-header-left{
          width: 120px;
          margin-right: 24px;
          .qrcode{
            width: inherit;
            height: 120px;
            background-color: #C1C4CB;
            margin-bottom: 16px;
          }
          .el-button{
            width: inherit;
          }
        }
        .edit-header-right{
          display: flex;
          flex-direction: column;
          flex: 2;
          .edit-header-link{
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: @secondary;
            font-size: 14px;
            user-select: none;
            span{
              color: @title;
            }
            img{
              cursor: pointer;
            }
          }
        }
      }
      .el-form-item{
        .el-form-item__label{
          color: @title;
          line-height: 100%;
          padding-bottom: 12px;
          span.icon-wenti_yiwen{
            color: @primary;
            font-size: 13px;
            cursor: pointer;
          }
        }
        .el-form-item__content{

        }
      }
      .read-tips{
        font-size: 12px;
        color: #C1C4CB;
      }
    }
  }
}
</style>
